//
//  JKPostVideoView.m
//  Baisi
//
//  Created by albert on 16/3/26.
//  Copyright (c) 2016年 albert. All rights reserved.
//

#import "JKPostVideoView.h"
#import "JKPostModel.h"
#import "UIImageView+WebCache.h"
#import "JKShowPictureViewController.h"

#import "FullViewController.h"
#import "VideoPlayView.h"
#import "JKDraggingVideoView.h"
#import "JKProgressView.h"
#import "JKVideoManager.h"

@interface JKPostVideoView () <VideoPlayViewDelegate>
@property (weak, nonatomic) IBOutlet JKAnimatedImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *playCountLabel;
@property (weak, nonatomic) IBOutlet UILabel *videoTimeLabel;

@property (weak, nonatomic) IBOutlet UIButton *playButton;
@property (weak, nonatomic) IBOutlet JKProgressView *progressView;
@property (weak, nonatomic) IBOutlet UIButton *downloadVideoButton;
@property (weak, nonatomic) IBOutlet UILabel *fileSizeLabel;

@property (nonatomic, strong) FullViewController *fullVc;
@property (nonatomic, weak) VideoPlayView *playView;
@property (nonatomic, weak) JKPostModel *currentSelectedModel;
@end

@implementation JKPostVideoView

- (FullViewController *)fullVc{
    if (_fullVc == nil) {
        _fullVc  = [[FullViewController alloc] init];
    }
    
    return _fullVc;
}

- (void)awakeFromNib{
    [super awakeFromNib];
    
    //给图片添加点击事件
    self.imageView.userInteractionEnabled = YES;
    [self.imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showPicture:)]];
    
    //发现控件明明设置好了，但是显示效果却有问题，就有可能是Autoresizing问题
    self.autoresizingMask = UIViewAutoresizingNone;
}

//模态窗口显示图片
- (void)showPicture:(UITapGestureRecognizer *)tap{
    
    CGPoint location = [tap locationInView:tap.view];
    
    location = [tap.view convertPoint:location toView:[UIApplication sharedApplication].delegate.window];
    
    [JKShowPictureViewController showWithPost:self.post touchPoint:location sourceVc:nil];
}

- (void)setPost:(JKPostModel *)post{
    _post = post;
    
    self.fileSizeLabel.hidden = _post.fileSize == nil;
    self.fileSizeLabel.text = [NSString stringWithFormat:@"%@MB", _post.fileSize];
    
    self.progressView.hidden = !_post.isDownloadingVideo;
    self.progressView.progress = _post.videoDownloadProgress;
    self.playButton.hidden = !self.progressView.hidden;
    self.downloadVideoButton.hidden = self.playButton.hidden;
    
    if (!_avoidSetImage) {
        
        [self.imageView fl_setImageWithURL:[NSURL URLWithString:post.large_image]];
    }
    
    //播放次数
    self.playCountLabel.text = [NSString stringWithFormat:@"%@播放",post.playcount];
    
    //视频时长
    NSInteger minute = [post.videotime integerValue] / 60;
    NSInteger second = [post.videotime integerValue] % 60;
    self.videoTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld", (long)minute, (long)second];
    
}

- (IBAction)playButtonClick:(UIButton *)sender {
    
    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
    
    JKDraggingVideoItem *item = [[JKDraggingVideoItem alloc] init];
    
    if ([JKVideoManager videoExistWithUrl:self.post.videouri]) {
        
        item.videoUrl = [NSURL fileURLWithPath:[JKVideoManager videoPathWithUrl:self.post.videouri]];
        
    }else{
        
        item.videoUrl = [NSURL URLWithString:self.post.videouri];
    }
    
    item.videoOriginalSize = CGSizeMake([self.post.width floatValue], [self.post.height floatValue]);
    item.videoImage = self.imageView.image;
    [JKDraggingVideoView showWithItem:item];
    
    /*
    //    if ([self.delegate respondsToSelector:@selector(postVideoView:clickVideoButton:)]) {
    //        [self.delegate postVideoView:self clickVideoButton:self.post];
    //    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:JKResetPlayerNotification object:nil];
    [self.playView resetPlayView];
    
    VideoPlayView *playView = [VideoPlayView videoPlayView];
    playView.imageView.image = self.imageView.image;
    playView.frame = CGRectMake(0, 0, self.width, self.height);
    
    playView.delegate = self;
    
    [self addSubview:playView];
    
    self.playView = playView;
    
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:self.post.videouri]];
    self.playView.playerItem = item;
     */
}

- (void)downloadVideo{
    
    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
    
    self.post.isDownloadingVideo = YES;
    self.downloadVideoButton.hidden = YES;
    
    self.progressView.hidden  = NO;
    self.playButton.hidden = YES;
    
    [JKVideoManager downloadVideoWithPostModel:self.post progress:^(NSProgress *downloadProgress) {
        
        JKLog(@"%@, %.2f", [NSThread currentThread], downloadProgress.fractionCompleted);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            self.post.videoDownloadProgress = downloadProgress.fractionCompleted;
            
            [self.progressView setProgress:self.post.videoDownloadProgress animated:YES];
        });
        
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        
        self.post.isDownloadingVideo = NO;
        self.post.videoDownloadProgress = 0;
        
        self.progressView.hidden = YES;
        self.playButton.hidden = NO;
        self.progressView.progress = 0;
        self.downloadVideoButton.hidden = NO;
        
        if (error) {
            
            [JKProgressHUD showErrorWithStatus:@"下载失败！"];
            
            return;
        }
        
        JKLog(@"%@", response);
    }];
}

- (IBAction)downloadVideoButtonClick:(UIButton *)sender {
    
    if (self.downloadVideoButtonClickBlock) {
        
        self.downloadVideoButtonClickBlock();
        
        return;
    }
    
    [self downloadVideo];
}

#pragma mark VideoPlayViewDelegate 视频播放时窗口模式与全屏模式切换
- (void)videoplayViewSwitchOrientation:(BOOL)isFull{
    
    if (isFull) {
        [[UIApplication sharedApplication].delegate.window.rootViewController presentViewController:self.fullVc animated:NO completion:^{
            self.playView.frame = self.fullVc.view.bounds;
            [self.fullVc.view addSubview:self.playView];
        }];
    } else {
        [self.fullVc dismissViewControllerAnimated:NO completion:^{
            self.fullVc = nil;
            self.playView.frame = CGRectMake(0, 0, self.width, self.height);
            [self addSubview:self.playView];
        }];
    }
}
@end
